<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/5
 * Time: 21:19
 */
namespace Admin\Controller;
use Think\Controller;
class CommonController extends Controller{

    public function __construct()
    {
        parent::__construct();
        $this->check_login();
    }

//    public function check_login()
//    {
//        if (!isset($_SESSION['user'])) {
//            $this->error('你还没有登录', U("Admin/User/login"));
//        }
//        $this->assign('user', $_SESSION['user']);
//    }

    private function check_login()
    {
        //如果session已经存在,直接退出
        if (isset($_SESSION['user'])) {
            $this->assign("user", $_SESSION['user']);
            return;
        }

        //判断token是否存在
        if (!isset($_COOKIE['token'])) {
            $this->error('你还没有登录',U('Admin/User/login'));
        }

        //检查token是否正确
        $data['token'] = $_COOKIE['token'];
        $model = M('user');
        $user = $model->where($data)->find();

        if (!$user) {
            $this->error('非法登录',U('Admin/User/login'));
        }

        //如果用户信息正确,存入session,方便使用
        $_SESSION['user'] = $user;
        $this->assign("user", $user);

    }
}